<template>
  <div style="width: 100%; height: 100%; position: relative;" v-loading="loading">
    <div class="mapEdit" v-if="isShowSet">
      <span>拖动，放大缩小地图到你想要的效果后，保存即可</span>
      <el-button size="mini" @click="preservation(true)">清除所有点</el-button>
      <el-button size="mini" @click="preservation(false)">保存</el-button>
    </div>
    <div
        id="mineMap"
        ref="mineMap"
        class="minmap"
        style="width: 100%; height: 100%"
    ></div>
  </div>
</template>

<script>
import {constructionRequest, SCREEN_CODE} from "@/utils/http/request";

const AMap = window.AMap;
export default {
  data() {
    return {
      loading: false,
      map: "",
      pointList: [],
      markers: [],
      curMarker: []
    };
  },
  created() {
    this.getData()
  },
  mounted() {

  },
  props: ["isShowSet"],
  methods: {
    //保存
    preservation(isClear) {
      let datalist = []
      if (!isClear)
        datalist = this.pointList.filter(item => item.datatype === '0').map(item => {
          return {
            datatype: "0",
            longitude: item.local[0],
            Latitude: item.local[1],
          }
        })

      this.loading = true
      constructionRequest
          .MapEdit({
            datalist: datalist,
            screenCode: SCREEN_CODE.construction,
          })
          .then((res) => {
            if (res.code === "01") {
              this.$message.success(res.msg || "修改成功");
              this.getData()
            }
          })
          .catch(() => {
          })
    },
    //获取数据
    getData() {
      this.loading = true
      constructionRequest
          .Map({
            screenCode: SCREEN_CODE.construction,
          })
          .then((res) => {
            if (res.code === "01") {
              let arr = []
              for (var i of res.datalist) {
                arr.push({
                  datatype: i.datatype,
                  local: [i.longitude * 1, i.Latitude * 1]
                })

              }
              this.pointList = arr
              // 初始化地图页面
              this.initMap();
            }
          })
          .catch(() => {
          })
          .finally(() => {
            this.loading = false;
          });
    },
    //   初始化地图页面
    initMap() {
      let self = this;
      let lat = window.localStorage.getItem('lat') || 32.017401
      let lng = window.localStorage.getItem('lng') || 118.826087
      let zoom = window.localStorage.getItem('zoom') || 5
      // window.localStorage.setItem('lat', center.lat)
      // window.localStorage.setItem('lng', center.lng)

      // 地图初始化应该在地图容器div已经添加到DOM树之后
      this.map = new AMap.Map("mineMap", {
        resizeEnable: true,
        center: [lng, lat], //中心点坐标
        // center: [this.defaultValue.longitude, this.defaultValue.latitude],
        zoom: zoom,
        mapStyle: "amap://styles/blue",
        showLabel: true, //不显示地图文字标记
        // pitch: 75, // 地图俯仰角度，有效范围 0 度- 83 度
        // viewMode: "3D", // 地图模式
        // terrain: true // 开启地形图
      });

      //遍历生成多个标记点
      for (let i = 0; i < this.pointList.length; i++) {
        if (this.pointList[i].datatype === '0') {
          new AMap.Marker({
            position: this.pointList[i].local, //不同标记点的经纬度
            map: self.map,
          });
        } else {
          new AMap.Marker({
            position: this.pointList[i].local, //不同标记点的经纬度
            map: self.map,
            icon: new AMap.Icon({
              image: require('../../assets/image/position.png'),
              size: new AMap.Size(32, 32),
              imageSize: new AMap.Size(32, 32)
            }),
          });

        }

      }
      if (!window.localStorage.getItem('lat'))
        this.map.setFitView();
      //添加点击事件
      this.map.on("click", (event) => {
        //  console.log(event.lnglat.getLng() + "," + event.lnglat.getLat());
        this.curMarker = []
        this.curMarker = [event.lnglat.getLng(), event.lnglat.getLat()]
        this.addMrker(event.lnglat);
        this.pointList.push({
          datatype: '0',
          local: [event.lnglat.lng, event.lnglat.lat]
        })
      });
      this.map.on('moveend', () => {
        let center = this.map.getCenter()
        window.localStorage.setItem('lat', center.lat)
        window.localStorage.setItem('lng', center.lng)
      })
      this.map.on('zoomend', () => {
        window.localStorage.setItem('zoom', this.map.getZoom())
      })
    },
    // 地图点击增加标记点
    addMrker(position) {
      if (!this.isShowSet) {
        return
      }
      const _this = this;
      // 根据点击位置经纬度查询详细信息
      const marker = new AMap.Marker({
        map: _this.map,
        position: new AMap.LngLat(position.lng, position.lat),
        size: new AMap.Size(60, 26),
        offset: new AMap.Pixel(-10, -33),
      });
      // 点击marker展示信息弹框
      // marker.on("click", (e) => {
      //   _this.addInfowindow(marker);
      // });

      _this.map.add(marker);
      marker.setMap(_this.map);
    },
  },
};
</script>

<style lang="scss" scoped>
.minmap {
  border-radius: 10px 10px 0 0;
}

.mapEdit {
  width: 100%;
  height: 50px;
  padding-top: 10px;
  background: #384768;
  border: 1px solid #64ade4;
  position: absolute;
  top: 0;
  z-index: 1;
  text-align: right;
  padding-right: 20px;
  color: #6ef7ff;

  span {
    margin-right: 10px;
  }
}
</style>
